﻿using System;
using System.Linq;
using System.Web.Caching;
using Microsoft.Practices.ServiceLocation;
using Pap.Core.CronJobs;
using Pap.Core.Logging;
using Pap.Core.Sync;
using Pap.Data.Abstraction.Utils;
using Pap.Services;
using Pap.Services.WorkflowEngine;
using Pap.Data;
using System.Configuration;
using System.IO;

namespace Pap.Web.Utils.CronJobs
{
    /// <summary>
    /// 
    /// </summary>
    public class DBSyncCornJob : ICronJob
    {

        public DBSyncCornJob()
        {
        }

        /// <summary>
        /// Gets the eexcution time.
        /// </summary>
        /// <returns>returns DBBackup Execution Time</returns>
        private TimeSpan GetEexcutionTime()
        {
            var AdminRepo = ServiceLocator.Current.GetInstance<IAdministrationRepository>();
            Guid committeeID = AdminRepo.FindCommittees(committee => true).FirstOrDefault().CommitteeID;

            DateTime execTime = DateTime.Parse(AdminRepo.GetSettingValue(committeeID,
                                                                    SettingKeys.DatabaseSynchTime));
            if (execTime > DateTime.Now)
                return execTime.TimeOfDay;
            return execTime.AddDays(1).TimeOfDay;
        }

        public TimeSpan SlidingTime
        {
            get { return GetEexcutionTime(); }
        }

        /// <summary>
        /// Gets the name of the job.
        /// </summary>
        /// <value>
        /// The name of the job.
        /// </value>
        public string JobName
        {
            get
            {
                return "SyncCornJob";
            }
        }

        /// <summary>
        /// Executes this instance.
        /// </summary>
        public void Execute()
        {
            try
            {
                SyncAgent agent = new SyncAgent();
                agent.Syncronize();
            }
            catch (Exception ex)
            {
                ServiceLocator.Current.GetInstance<ILog>().RaiseError(ex);
            }
        }
    }
}
